import axios from 'axios'
import { ElMessage } from 'element-plus'
//1.利用axios的create去创建一个实例
let request = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 5000,
})

//2.使用请求拦截器
request.interceptors.request.use(config => {
  //返回配置对象
  //config.headers.token = localStorage.getItem('token') || 'Admin Token'
  return config
})

//3.使用响应拦截器
request.interceptors.response.use(
  response => {
    return response
  },
  error => {
    let message = ''
    let status = error.response?.status

    switch (status) {
      case 401:
        message = 'token失效'
        break
      case 403:
        message = '没有权限'
        break
      case 404:
        message = '请求资源不存在'
        break
      case 500:
        message = '服务器错误'
      default:
        message = '网络错误'
    }
    //提示错误信息
    ElMessage.error(message)

    return Promise.reject(error)
  }
)

export default request
